<?php
// +----------------------------------------------------------------------
// | XiaMiCMF - 代码如诗
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://shujuwajue.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小虾米 <509129@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;

use Common\Lib\Think\Page;
use Helper\Controller\UploadController;
use Common\Controller\AdminBaseController;
use Admin\Model\AdminModel;

class FileManagerController extends AdminBaseController
{
    const CNAME = '文档';
    const SAVE_PATH = 'attachments';

    protected $fileManager_model;
    protected $fileManagerType_model;

    public function _initialize() {
        parent::_initialize();
        $this->fileManager_model = D("FileManager");
        $this->fileManagerType_model = D("FileManagerType");
    }

    /**
     * 文档管理列表
     */
    public function index() {

        if (AdminModel::DEFAULT_ADMIN == x_get_admin_id()) {
            $this->error('默认系统管理员账号不能进行文档上传',U('listAll'));
        }
        $where['admin_id'] = x_get_admin_id();
        $count = $this->fileManager_model->where($where)->count();
        $page = new Page($count, C('PAGE_LIST_ROWS'));
        $show = $page->show();
        $list = $this->fileManager_model->where($where)->limit($page->firstRow . ',' . $page->listRows)->select();

        //文档类型
        $types = $this->fileManagerType_model->fetchAll();
        $this->assign('types', $types);
        $this->assign('list', $list); // 赋值数据集
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('count', $count);
        $this->display(); // 输出模板

    }

    public function listAll() {

        $where = array();
        $nickname = I('nickname', '', 'htmlspecialchars');
        if (!empty($nickname)) {
            $where['b.nickname'] = array('LIKE', '%' . $nickname . '%');
            $this->assign('nickname', $nickname);
        }

        $type_id = I('type_id', '', 'intval');
        if (!empty($type_id)) {
            $where['a.type_id'] = $type_id;
            $this->assign('type_id', $type_id);
        }

        //文档类型
        $types = $this->fileManagerType_model->fetchAll();
        $this->assign('types', $types);

        if (!empty($nickname) && empty($type_id)) { //根据类型进行选择

            //统计该上传者每个类型的数量
            $countArr = $this->fileManager_model->alias('a')
                ->join('__ADMIN__ b ON b.admin_id= a.admin_id')
                ->group('a.type_id')
                ->where($where)
                ->getField('type_id,count(*) as count');

            //统计该上传者当天分类型数量
            $where['a.create_time'] = array('GT', date('Y-m-d'));
            $dayCountArr = $this->fileManager_model->alias('a')
                ->join('__ADMIN__ b ON b.admin_id= a.admin_id')
                ->group('a.type_id')
                ->where($where)
                ->getField('type_id,count(*) as count');

            $this->assign('dayCountArr', $dayCountArr);
            $this->assign('countArr', $countArr);
            $this->display('listAllStep1'); // 输出模板
        } elseif(!empty($nickname) && !empty($type_id)) {  //根据选择的类型和上传者进行列出文件
            $count = $this->fileManager_model->alias('a')
                ->join('__ADMIN__ b ON b.admin_id= a.admin_id')
                ->where($where)->count();
            $page = new Page($count, C('PAGE_LIST_ROWS'));
            $show = $page->show();
            $list = $this->fileManager_model->alias('a')
                ->join('__ADMIN__ b ON b.admin_id= a.admin_id')
                ->where($where)->limit($page->firstRow . ',' . $page->listRows)
                ->order(array('file_id' => 'DESC'))
                ->field('a.*,b.nickname')
                ->select();


            $this->assign('list', $list); // 赋值数据集
            $this->assign('page', $show); // 赋值分页输出
            $this->assign('count', $count);
            $this->display('listAllStep2'); // 输出模板
        } else {
            $flag = I('flag');

            //项目工程的角色值
            $project_role_ids = array();
            $config_project_role_ids = C('PROJECT_ROLE_ID');
            if (!empty($config_project_role_ids)) {
                $project_role_ids = explode(',', $config_project_role_ids);
            }

            $admin_model = D('Admin');


            if ($flag == 'uploaded') { //当日已上传

                $admins = $admin_model->fetchAll();
                foreach ($admins as $k => $v) {
                    $admins[$k] = $admin_model->_format($v);
                    $intersect = array_intersect($admins[$k]['role_ids'], $project_role_ids);
                    if (empty($intersect)) {
                        unset($admins[$k]);
                    }
                }
                // 统计已上传的用户
                $where['create_time'] = array('GT', date('Y-m-d'));
                $user_uploaded_arr = $this->fileManager_model
                    ->distinct(true)
                    ->where($where)->getField('admin_id,create_time');
                foreach ($admins as $admin_id => $admin) {

                    if (!isset($user_uploaded_arr[$admin_id]) || $admin['status'] == 0
                        ||!in_array($admin_id, $project_role_ids)) {
                        unset($admins[$admin_id]);
                    }
                }
                $this->assign('list', $admins);

            } else { //所有允许的项目组
                $where = array();
                // 分页
                $count = $admin_model->where($where)->count();
                $page = new Page($count, C('PAGE_LIST_ROWS'));
                $show = $page->show();
                $list = $admin_model->where($where)->limit($page->firstRow . ',' . $page->listRows)->select();
                foreach ($list as $k => $v) {
                    $list[$k] = $admin_model->_format($v);
                    $intersect = array_intersect($list[$k]['role_ids'], $project_role_ids);
                    if (empty($intersect)) {
                        unset($list[$k]);
                    }
                }

                $this->assign('page', $show); // 赋值分页输出
                $this->assign('count', $count);
                $this->assign('list', $list);
            }
            $this->assign('flag', $flag);
            $this->display('listAll'); // 输出模板
        }
    }

    /**
     * 文档报表
     */
    public function report() {

        // 30天的数据统计
        $result = $this->fileManager_model->group('date')
            ->getField("DATE_FORMAT(create_time, '%m-%d') as date,count(*) as count");
        $list = array();
        for($i=29;$i>=0;$i--) {
            $daytime = date('m-d', strtotime("-$i day"));
            $list[$daytime]= $result[$daytime]['count'];
        }
        $this->assign('list', $list);
        $this->display(); // 输出模板
    }

    /**
     * 上传文档
     */
    public function upload() {
        if (AdminModel::DEFAULT_ADMIN == x_get_admin_id()) {
            $this->error('默认系统管理员账号不能进行文档上传',U('listAll'));
        }
        if (IS_POST) {
            $result = A('Helper/Upload')->uploadFile(
                self::SAVE_PATH,
                UploadController::TYPE_FILE
            );
            if (empty($result['status'])) {
                $this->error('上传失败:' . $result['message']);
            }

            $_POST['file_name'] = $result['name'];
            $_POST['file_path'] = $result['filepath'];

            $data = $this->fileManager_model->create();
            if ($data) {
                $data['admin_id'] = session('admin.admin_id');
                $id = $this->fileManager_model->add($data);
                if ($id) {
                    //获取url 进行预览内容预热
                    $url = x_get_file_download_url($id);
                    $curlIns =new \Common\Lib\Net\Curl();
                    $curlIns->get($url);
                    $this->success('上传成功', U('index'));
                } else {
                    $this->error('上传失败');
                }
            } else {
                $this->error($this->fileManager_model->getError());
            }
        } else {
            $types = $this->fileManagerType_model->fetchAll();
            $this->assign('types', $types);
            $this->display();
        }
    }

    /*
     * 预览文档
     * */
    public function view(){
        $file_id = I('get.file_id', 0, 'intval');
        $detail = $this->fileManager_model->find($file_id);
        if (empty($detail)) {
            $this->error('预览的文档不存在');
        }
        $url = x_get_file_download_url($detail['file_path']);
        $this->assign('url', urlencode($url));
        $this->display();
    }

    /**
     * 下载文档
     */
    public function download() {
        $file_id = I('get.file_id', 0, 'intval');
        $detail = $this->fileManager_model->find($file_id);
        if (empty($detail)) {
            $this->error('下载的文档不存在');
        }
        $_GET['file_path'] = $detail['file_path'];
        $_GET['file_name'] = $detail['file_name'];
        //$_GET['style'] = '-thumbnail300X300';
        A('Helper/Download')->index();
        exit();
    }

    /**
     * 删除文档
     */
    public function delete() {
        $file_id = I('post.file_id',0,'intval');
        if (is_numeric($file_id)) {
            $detail = $this->fileManager_model->find($file_id);
            $delete = $this->fileManager_model->delete($file_id);
            if (!empty($detail) && !empty($delete)) { //同时删除本地文件
                x_delete_file($detail['file_path']);
            }
            $this->success('删除成功', U('index'));
        } elseif (is_array($file_id)) {
            $this->fileManager_model->delete(implode(',', $file_id));
            $this->success('删除成功', U('index'));
        } else {
            $this->error('请选择要删除的' . self::CNAME);
        }
    }
}